package cn.com.twoke.easyproject.config.redis;

import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.TransportMode;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Author: CchenQs
 * @Date: 2020/7/14
 * @Description:
 */
@Configuration
public class RedisConfiguration {

	/**
	 * redis序列化配置
	 * @param factory
	 * @return
	 */
	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(factory);
		StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
		// key的序列化方式采用stringRedisSerializer
		template.setKeySerializer(stringRedisSerializer);
		template.setHashKeySerializer(stringRedisSerializer);
		FastJson2JsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJson2JsonRedisSerializer<>(Object.class);
		// value序列化方式采用fastJsonRedisSerializer
		template.setValueSerializer(fastJsonRedisSerializer);
		template.setHashValueSerializer(fastJsonRedisSerializer);
		template.afterPropertiesSet();
		return template;
	}

	/**
	 * @return
	 * @Cacheable序列化配置 此处不指定过期时间，需要指定过期时间的场景使用redisUtil进行操作
	 */
	@Bean
	public RedisCacheConfiguration redisCacheConfiguration() {
		return RedisCacheConfiguration.defaultCacheConfig()
				.serializeKeysWith(
						RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
				.serializeValuesWith(RedisSerializationContext.SerializationPair
						.fromSerializer(new FastJson2JsonRedisSerializer<>(Object.class)));
	}


	@Bean
	public RedissonClient redissonClient(RedisProperties redisProperties) {
		Config config = new Config();
		config.setTransportMode(TransportMode.NIO);
		if (StringUtils.isEmpty(redisProperties.getPassword())) {
			config.useSingleServer().setAddress("redis://" + redisProperties.getHost() + ":" + redisProperties.getPort())
					.setDatabase(redisProperties.getDatabase());
		} else {
			config.useSingleServer().setAddress("redis://" + redisProperties.getHost() + ":" + redisProperties.getPort())
					.setPassword(redisProperties.getPassword())
					.setDatabase(redisProperties.getDatabase());
		}
		return Redisson.create(config);
	}



}
